﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAL;
using Models;

namespace 包覆门.PackageManager
{
    public partial class PackageEditing : Form
    {
        public PackageEditing()
        {
            InitializeComponent();
        }
        public bool IsNew { get; set; }
        public string EditingId { get; set; }
        private PackageDAL dal = new PackageDAL();
        //保存
        private void btnsave_Click(object sender, EventArgs e)
        {
            Packages p = new Packages();
            p.Ptype = this.tbptype.Text.Trim();
            p.Price = this.tbprice.Text.Trim();
            if (ValidateData(p))
            {
                if (IsNew)
                {
                    int result = dal.SaveData(p);
                    if (result == 1)
                    {
                        MessageBox.Show("保存成功");
                        DialogResult = DialogResult.OK;
                    }
                    else {
                        MessageBox.Show("保存失败");
                        DialogResult = DialogResult.No;
                    }
                }
                else
                {
                    p.Pid = Convert.ToInt32(EditingId);
                    int result = dal.UpdateData(p);
                    if (result == 1)
                    {
                        MessageBox.Show("保存成功");
                        DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        MessageBox.Show("保存失败");
                        DialogResult = DialogResult.No;
                    }
                }
            }
        }
        //取消
        private void btncancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.No;
        }

        //窗体加载
        private void PackageEditing_Load(object sender, EventArgs e)
        {
            if (IsNew) { } else {
                Packages p = dal.GetPackagesById(EditingId);
                this.tbptype.Text = p.Ptype;
                this.tbprice.Text = p.Price;
            }
        }
        private bool ValidateData(Packages p) { 
            bool flag = true;
            if (string.IsNullOrWhiteSpace(p.Ptype)) {
                flag = false;
                MessageBox.Show("包装类别不能为空");
                return flag;
            }
            return flag;
        }
        //输入数字
        private void tbprice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.' && this.tbprice.Text.IndexOf(".") != -1)
            {
                e.Handled = true;
            }

            if (!((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == '.' || e.KeyChar == 8))
            {
                e.Handled = true;
            }  
        }
    }
}
